/**
 * 工具类
 * @type {{toMapList: util.toMapList, toMap: util.toMap}}
 */
import Vue from 'vue'
const util = {
  toMap: function (arr, idField) {
    if (!arr) return {};

    var map = {};
    arr.forEach(function (item) {
      var field = item[idField];
      map[field] = item;
    });
    return map;
  },

  toMapList: function (arr, idField, sortField) {
    if (!arr) return {};

    var map = {};
    arr.forEach(function (item) {
      var field = item[idField];
      let list = [];
      if (map[field]) {
        list = map[field];
      }
      list.push(item);
      if (sortField && list.length >= 2) {
        list.sort(function (a, b) { return (a[sortField] < b[sortField]) ? 1 : -1; });
      }
      map[field] = list;
    });
    return map;
  },


  // 上移、下移
  changeSortIndex:function (type,list,index) {
    var changeItemList = [];
    if (type == 1) {
      if (index == 0) return;

      list[index - 1].sortIndex++;
      list[index].sortIndex--;

      var temp = list[index - 1];
      Vue.set(list, index - 1, list[index])
      Vue.set(list, index, temp)

      changeItemList = [
        {
          id: list[index - 1].id,
          sortIndex: list[index - 1].sortIndex
        },
        {
          id: list[index].id,
          sortIndex: list[index].sortIndex
        }
      ];

    } else if (type == 2) {
      if (index == list.length - 1) return;
      list[index + 1].sortIndex--;
      list[index].sortIndex++;

      var temp = list[index + 1];
      Vue.set(list, index + 1, list[index])
      Vue.set(list, index, temp)

      changeItemList = [
        {
          id: list[index + 1].id,
          sortIndex: list[index + 1].sortIndex
        },
        {
          id: list[index].id,
          sortIndex: list[index].sortIndex
        }
      ];
    }

    if (changeItemList.length == 0) return;
  }
}

export default util
